<?php
/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 数据同步功能接口 - 同步数据至本地JSON文件
 * 尊重劳动成果是一种美德
 */

date_default_timezone_set('Asia/Shanghai');
ini_set('display_errors', 0);
error_reporting(0);
ini_set('session.save_path', sys_get_temp_dir());
session_start();

// 日志函数已禁用
// function writeSyncLog($message, $level = 'INFO') {}

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => '请先登录'], JSON_UNESCAPED_UNICODE);
    exit;
}

header('Content-Type: application/json; charset=utf-8');

$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action === 'sync_data') {
    try {
        // writeSyncLog('=== 数据同步请求开始 ===');
        
        require_once '../config.php';
        require_once '../classes/H3OpenApiClient.php';
        
        $config = require '../config.php';
        $client = new H3OpenApiClient($config);
        
        // 获取过滤参数
        $schemaKey = $_GET['schema'] ?? 'default';
        $dateType = $_GET['date_type'] ?? 'today';
        $startDate = $_GET['start_date'] ?? date('Y-m-d');
        $endDate = $_GET['end_date'] ?? date('Y-m-d');
        $dataLimit = intval($_GET['data_limit'] ?? 10000);
        $sortOrder = $_GET['sort_order'] ?? 'desc';
        
        // writeSyncLog("同步参数 - Schema: {$schemaKey}, 日期: {$startDate} ~ {$endDate}, 限制: {$dataLimit}");
        
        // 验证数据限制
        if ($dataLimit > 50000) {
            $dataLimit = 50000; // 最大限制5万条
        }
        
        // 获取表单配置
        $schemas = $config['schemas'] ?? [];
        if (!isset($schemas[$schemaKey])) {
            // writeSyncLog("错误: 表单不存在 - {$schemaKey}", 'ERROR');
            throw new Exception('表单不存在');
        }
        $schemaConfig = $schemas[$schemaKey];
        $schemaCode = $schemaConfig['schema_code'];
        $schemaName = $schemaConfig['schema_name'] ?? '未知表单';
        
        // writeSyncLog("使用表单: {$schemaName} ({$schemaCode})");
        
        // 构建时间过滤条件
        $todayStart = $startDate . ' 00:00:00';
        $todayEnd = $endDate . ' 23:59:59';
        
        $filter = [
            'FromRowNum' => 0,
            'ToRowNum' => $dataLimit,
            'RequireCount' => true,
            'ReturnItems' => [],
            'SortByCollection' => [
                [
                    'ItemName' => 'CreatedTime',
                    'Direction' => $sortOrder === 'asc' ? 'Ascending' : 'Descending'
                ]
            ],
            'Matcher' => [
                'Type' => 'And',
                'Matchers' => [
                    [
                        'Type' => 'ItemMatcher',
                        'ItemName' => 'CreatedTime',
                        'Operator' => 'GreaterThanOrEqual',
                        'Value' => $todayStart
                    ],
                    [
                        'Type' => 'ItemMatcher',
                        'ItemName' => 'CreatedTime',
                        'Operator' => 'LessThanOrEqual',
                        'Value' => $todayEnd
                    ]
                ]
            ]
        ];
        
        $result = $client->loadBizObjects($schemaCode, $filter);
        
        if (empty($result)) {
            echo json_encode([
                'success' => true,
                'message' => '暂无数据需要同步',
                'data_count' => 0,
                'file_path' => null
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
        
        // 处理数据并过滤指定日期范围的数据
        $processedData = [];
        
        foreach ($result as $item) {
            $createdTime = $item['CreatedTime'] ?? '';
            
            // 验证是否在指定日期范围内
            if (!empty($createdTime)) {
                $itemDate = date('Y-m-d', strtotime($createdTime));
                if ($itemDate < $startDate || $itemDate > $endDate) {
                    continue;
                }
            }
            
            $processedItem = [
                'id' => $item['ObjectId'] ?? '',
                'title' => $item['Name'] ?? '无标题',
                'created_time' => $createdTime,
                'image_fields' => [],
                'all_fields' => []
            ];
            
            // 从配置文件读取字段配置
            $imageFields = $schemaConfig['image_fields'] ?? [];
            $attachmentFields = $schemaConfig['attachment_fields'] ?? [];
            
            // 处理所有字段
            foreach ($item as $fieldCode => $value) {
                $isImage = in_array($fieldCode, $imageFields);
                $isAttachment = in_array($fieldCode, $attachmentFields);
                
                $displayValue = '';
                if (is_null($value) || $value === '') {
                    $displayValue = '空';
                } else if (is_array($value) || is_object($value)) {
                    $displayValue = json_encode($value, JSON_UNESCAPED_UNICODE);
                } else {
                    $displayValue = (string)$value;
                }
                
                $processedItem['all_fields'][$fieldCode] = [
                    'field_name' => $fieldCode,
                    'field_code' => $fieldCode,
                    'raw_value' => $value,
                    'display_value' => $displayValue,
                    'is_image' => $isImage,
                    'is_attachment' => $isAttachment
                ];
                
                // 如果是图片字段，添加到图片字段数组
                if ($isImage) {
                    $processedItem['image_fields'][] = [
                        'field_code' => $fieldCode,
                        'field_name' => $fieldCode,
                        'value' => $value
                    ];
                }
            }
            
            $processedData[] = $processedItem;
        }
        
        // 创建同步数据包
        $syncData = [
            'sync_info' => [
                'sync_time' => date('Y-m-d H:i:s'),
                'date_range' => [
                    'start_date' => $startDate,
                    'end_date' => $endDate,
                    'date_type' => $dateType
                ],
                'data_count' => count($processedData),
                'schema_code' => $schemaCode,
                'schema_name' => $schemaName,
                'filters' => [
                    'data_limit' => $dataLimit,
                    'sort_order' => $sortOrder
                ]
            ],
            'data' => $processedData
        ];
        
        // 创建保存目录
        $syncDir = '../sync_data/';
        if (!is_dir($syncDir)) {
            mkdir($syncDir, 0755, true);
        }
        
        // 生成文件名
        $fileName = 'sync_' . $startDate;
        if ($startDate !== $endDate) {
            $fileName .= '_to_' . $endDate;
        }
        $fileName .= '_' . date('His') . '.json';
        $filePath = $syncDir . $fileName;
        
        // 保存到JSON文件
        $jsonData = json_encode($syncData, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        $saveResult = file_put_contents($filePath, $jsonData);
        
        if ($saveResult === false) {
            // writeSyncLog("错误: 文件保存失败 - {$fileName}", 'ERROR');
            throw new Exception('保存文件失败，请检查目录权限');
        }
        
        $dataCount = count($processedData);
        $fileSize = formatBytes($saveResult);
        // writeSyncLog("同步成功 - 数据: {$dataCount} 条, 文件: {$fileName} ({$fileSize})");
        // writeSyncLog('=== 数据同步请求结束 ===');
        
        echo json_encode([
            'success' => true,
            'message' => '数据同步成功',
            'data_count' => count($processedData),
            'file_path' => $fileName,
            'file_size' => formatBytes($saveResult),
            'sync_time' => date('Y-m-d H:i:s')
        ], JSON_UNESCAPED_UNICODE);
        
    } catch (Exception $e) {
        $errorMsg = $e->getMessage();
        // writeSyncLog("同步异常: {$errorMsg}", 'ERROR');
        // writeSyncLog('=== 数据同步请求异常结束 ===');
        
        echo json_encode([
            'success' => false,
            'message' => '同步异常: ' . $errorMsg
        ], JSON_UNESCAPED_UNICODE);
    }
} else {
    echo json_encode(['success' => false, 'message' => '无效的操作'], JSON_UNESCAPED_UNICODE);
}

/**
 * 格式化文件大小
 */
function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    
    for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
        $bytes /= 1024;
    }
    
    return round($bytes, $precision) . ' ' . $units[$i];
}
?>